<template>
  <BasicModal
    v-bind="$attrs"
    :title="t('common.upload')"
    @register="register"
    @ok="handleSubmit"
    @cancel="handleClose"
    :destroyOnClose="true"
    :canFullscreen="false"
    :width="1000"
    :okText="t('component.cropper.okText')"
  >
    <div :class="prefixCls">
      <div :class="`${prefixCls}-left`">
        <div :class="`${prefixCls}-cropper`">
          <CropperImage
            ref="refCropper"
            v-if="src"
            :src="src"
            @cropend="handleCropend"
            @ready="handleReady"
            height="300px"
          />
        </div>
        <div :class="`${prefixCls}-toolbar`">
          <Upload
            :fileList="[]"
            accept="image/*"
            :beforeUpload="handleBeforeUpload"
            :customRequest="customUpload"
          >
            <Tooltip :title="t('component.cropper.selectImage')" placement="bottom">
              <a-button size="small" preIcon="ant-design:upload-outlined" type="primary" />
            </Tooltip>
          </Upload>
          <Space>
            <Tooltip :title="t('component.cropper.btn_reset')" placement="bottom">
              <a-button
                type="primary"
                preIcon="ant-design:reload-outlined"
                size="small"
                :disabled="!src"
                @click="handlerToolbar('reset')"
              />
            </Tooltip>
            <Tooltip :title="t('component.cropper.btn_rotate_left')" placement="bottom">
              <a-button
                type="primary"
                preIcon="ant-design:rotate-left-outlined"
                size="small"
                :disabled="!src"
                @click="handlerToolbar('rotate', -45)"
              />
            </Tooltip>
            <Tooltip :title="t('component.cropper.btn_rotate_right')" placement="bottom">
              <a-button
                type="primary"
                preIcon="ant-design:rotate-right-outlined"
                size="small"
                :disabled="!src"
                @click="handlerToolbar('rotate', 45)"
              />
            </Tooltip>
            <Tooltip :title="t('component.cropper.btn_scale_x')" placement="bottom">
              <a-button
                type="primary"
                preIcon="vaadin:arrows-long-h"
                size="small"
                :disabled="!src"
                @click="handlerToolbar('scaleX')"
              />
            </Tooltip>
            <Tooltip :title="t('component.cropper.btn_scale_y')" placement="bottom">
              <a-button
                type="primary"
                preIcon="vaadin:arrows-long-v"
                size="small"
                :disabled="!src"
                @click="handlerToolbar('scaleY')"
              />
            </Tooltip>
            <Tooltip :title="t('component.cropper.btn_zoom_in')" placement="bottom">
              <a-button
                type="primary"
                preIcon="ant-design:zoom-in-outlined"
                size="small"
                :disabled="!src"
                @click="handlerToolbar('zoom', 0.1)"
              />
            </Tooltip>
            <Tooltip :title="t('component.cropper.btn_zoom_out')" placement="bottom">
              <a-button
                type="primary"
                preIcon="ant-design:zoom-out-outlined"
                size="small"
                :disabled="!src"
                @click="handlerToolbar('zoom', -0.1)"
              />
            </Tooltip>
          </Space>
        </div>
      </div>
      <div :class="`${prefixCls}-right`">
        <div :class="`${prefixCls}-preview`">
          <img :src="previewSource" v-if="previewSource" :alt="t('component.cropper.preview')" />
        </div>
        <template v-if="previewSource">
          <div :class="`${prefixCls}-group`">
            <Avatar :src="previewSource" size="large" />
            <Avatar :src="previewSource" :size="48" />
            <Avatar :src="previewSource" :size="64" />
            <Avatar :src="previewSource" :size="80" />
          </div>
        </template>
      </div>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { Space, Upload, Avatar, Tooltip } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { CropperImage } from '/@/components/Cropper';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { UploadThumbnail } from '/@/api/demo/partManager';

  const { t } = useI18n();
  const { createMessage } = useMessage();
  const { prefixCls } = useDesign('cropper-am');
  const emit = defineEmits(['success', 'register']);
  const filename = ref('');
  const scaleX = ref(1);
  const scaleY = ref(1);
  const src = ref('');
  const previewSource = ref('');
  const cropper = ref<any>();
  // 缩略图文件
  const thumbnailFile = ref<any>(null);
  // 当前零件信息
  const partInfo = ref<any>({});

  // 提交
  const handleSubmit = async () => {
    const param = new FormData();
    param.append('file', thumbnailFile.value);
    await UploadThumbnail(partInfo.value.id, param);
    createMessage.success(t('common.uploadSuccess'));
    emit('success');
    handleClose();
  };

  // 关闭弹窗
  const handleClose = () => {
    filename.value = '';
    scaleX.value = 1;
    scaleY.value = 1;
    src.value = '';
    previewSource.value = '';
    thumbnailFile.value = null;
    cropper.value?.destroy();
    closeModal();
  };

  const handleBeforeUpload = (file: File) => {
    thumbnailFile.value = file;
    const reader = new FileReader();
    reader.readAsDataURL(file);
    src.value = '';
    previewSource.value = '';
    reader.onload = function (e) {
      src.value = (e.target?.result as string) ?? '';
      filename.value = file.name;
    };
    return false;
  };

  const handleCropend = ({ imgBase64 }) => {
    previewSource.value = imgBase64;
  };

  const handleReady = (cropperInstance: Cropper) => {
    cropper.value = cropperInstance;
  };

  const handlerToolbar = (event: string, arg?: number) => {
    if (event === 'scaleX') {
      scaleX.value = arg = scaleX.value === -1 ? 1 : -1;
    }
    if (event === 'scaleY') {
      scaleY.value = arg = scaleY.value === -1 ? 1 : -1;
    }
    cropper?.value?.[event]?.(arg);
  };

  // 定义弹窗是否可见
  const [register, { setModalProps, closeModal }] = useModalInner((data) => {
    setModalProps({ confirmLoading: false });
    partInfo.value = data.record;
  });
</script>

<style lang="less">
  @prefix-cls: ~'@{namespace}-cropper-am';

  .@{prefix-cls} {
    display: flex;

    &-left,
    &-right {
      height: 340px;
    }

    &-left {
      width: 55%;
    }

    &-right {
      width: 45%;
    }

    &-cropper {
      height: 300px;
      background: #eee;
      background-image: linear-gradient(
          45deg,
          rgb(0 0 0 / 25%) 25%,
          transparent 0,
          transparent 75%,
          rgb(0 0 0 / 25%) 0
        ),
        linear-gradient(
          45deg,
          rgb(0 0 0 / 25%) 25%,
          transparent 0,
          transparent 75%,
          rgb(0 0 0 / 25%) 0
        );
      background-position: 0 0, 12px 12px;
      background-size: 24px 24px;
    }

    &-toolbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 10px;
    }

    &-preview {
      width: 220px;
      height: 220px;
      margin: 0 auto;
      overflow: hidden;
      border: 1px solid @border-color-base;
      border-radius: 50%;

      img {
        width: 100%;
        height: 100%;
      }
    }

    &-group {
      display: flex;
      padding-top: 8px;
      margin-top: 8px;
      border-top: 1px solid @border-color-base;
      justify-content: space-around;
      align-items: center;
    }
  }
</style>
